package com.qujia.web.controller.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.qujia.common.core.domain.model.LoginUser;
import com.qujia.common.core.redis.RedisCache;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.station.domain.Enterprise;
import com.qujia.station.service.IEnterpriseService;
import com.qujia.system.domain.HttpRequestUtil;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.qujia.common.config.QuJiaConfig;
import com.qujia.common.constant.Constants;
import com.qujia.common.core.domain.AjaxResult;
import com.qujia.common.utils.StringUtils;
import com.qujia.common.utils.file.FileUploadUtils;
import com.qujia.common.utils.file.FileUtils;
import com.qujia.framework.config.ServerConfig;

import java.util.Objects;

/**
 * 通用请求处理
 *
 * @author qujia
 */
@RestController
public class CommonController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IEnterpriseService enterpriseService;


    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.isValidFilename(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = QuJiaConfig.getDownloadPath() + fileName;

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 下载文件去除时间戳前缀
     * */
    @GetMapping("common/downloadFile")
    public void fileDownloadExcel(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.isValidFilename(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = fileName.substring(fileName.indexOf("_") + 1);
            String filePath = QuJiaConfig.getDownloadPath() + fileName;

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = QuJiaConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String urls = serverConfig.getUrl() + fileName;
            System.out.println("----===============fileName:"+fileName);
            System.out.println("----===============getImageurl:"+ QuJiaConfig.getImageUrl() );
            System.out.println("----===============getImageurl:"+ QuJiaConfig.getProfile());
            String url = QuJiaConfig.getImageUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            return ajax;
        }
        catch (Exception e)
        {
            log.info(e.toString());
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 支付项目调用上传请求
     */
    @PostMapping("/common/uploadFile")
    public AjaxResult apiPayUploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = QuJiaConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = QuJiaConfig.getImageUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            return ajax;
        }
        catch (Exception e)
        {
            log.info(e.toString());
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求
     * TODO
     */
    @PostMapping("/wxUpload")
    public AjaxResult upload(MultipartFile file, Long enterpriseId) {

        try {
//            LoginUser current= SecurityUtils.getLoginUser();
            if (enterpriseId == null) {
                return AjaxResult.error("未选择油企");
            }
            if (file == null) {
                return AjaxResult.error("请上传图片");
            }
            Enterprise enterprise = enterpriseService.selectEnterpriseById(enterpriseId);
            String accessToken = "";
            String reqJson="";
            String tokeurl = "https://mp.huijy.net/prod/getAccessTokenFromSaas";
            accessToken = redisCache.getCacheObject("access_token_" + enterprise.getGzhAppId());
            if ("".equals(accessToken) || accessToken == null) {
                if (Objects.isNull(enterprise.getGzhAppSecret())){
                    reqJson = "{\n" +
                            "    \"appId\":\"" + enterprise.getGzhAppId() + "\"\n" + "}";
                }else {
                    reqJson = "{\n" +
                            "    \"appId\":\"" + enterprise.getGzhAppId() + "\",\n" +
                            "    \"appSecret\":\"" + enterprise.getGzhAppSecret() + "\"\n" +
                            "}";
                }
                JSONObject tokenmessage = HttpRequestUtil.getHttpsRequestData(tokeurl, "POST", reqJson);
                Integer retCode = tokenmessage.getInteger("retCode");
                if (retCode != 0) {
                    return AjaxResult.error("拉取accesstoken失败");
                }

                accessToken = tokenmessage.getString("data");
            }
            if (StringUtils.isBlank(accessToken)) {
                return AjaxResult.error("未查到accessToken");
            }


            OkHttpClient client = new OkHttpClient().newBuilder().build();
//            MediaType mediaType = MediaType.parse("text/plain");
            okhttp3.RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("media", file.getOriginalFilename(), okhttp3.RequestBody.create(MediaType.parse("application/octet-stream"), file.getBytes()))
//                    .addFormDataPart("media", file.getName(), okhttp3.RequestBody.create(MediaType.parse("application/octet-stream"), file))
                    .build();
            String url = String.format("https://api.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s", accessToken, "image");
            okhttp3.Request request = new okhttp3.Request.Builder()
                    .url(url)
                    .method("POST", body)
                    .build();
            okhttp3.Response response = client.newCall(request).execute();
            okhttp3.ResponseBody responseBody = response.body();
            if (responseBody == null) {
                return AjaxResult.error("上传图片失败");
            }
            JSONObject jsonObject = JSONObject.parseObject(responseBody.string());
//            UploadTempMediaResult uploadTempMediaResult = JSONObject.parseObject(responseBody.string(), UploadTempMediaResult.class);
//            log.info("把媒体文件上传到微信服务器[OkHttpClient] 返回结果 {}", JSONObject.toJSONString(uploadTempMediaResult));

//             ajax = AjaxResult.success()
            return AjaxResult.success("上传成功，已经获得媒体id，请复制后使用", jsonObject.getString("media_id"));
//            return uploadTempMediaResult;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @PostMapping(value = "/test2")
    public void uploadMedia3(@RequestPart("media") MultipartFile media) {
//        log.info("把媒体文件上传到微信服务器[OkHttpClient] 请求参数 type[{}] filename[{}]", type, file.getName());
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
//            MediaType mediaType = MediaType.parse("text/plain");
            okhttp3.RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("media", media.getOriginalFilename(), okhttp3.RequestBody.create(MediaType.parse("application/octet-stream"), media.getBytes()))
//                    .addFormDataPart("media", file.getName(), okhttp3.RequestBody.create(MediaType.parse("application/octet-stream"), file))
                    .build();
            String url = String.format("https://api.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s", "61_BG3-LNJii1YW8AtPO8ILAY23t644oMLqUcxTcG1L7pdT7dxve93ktODMAO-A3NDky2dvKG0lmtx2PPrScOQT_S0jaDndprKhc-oYZFwoncsuLuAf2V6rU71bVGHUwr9qLc7ugCQKn_beDcfPZJZeABATDT", "image");
            okhttp3.Request request = new okhttp3.Request.Builder()
                    .url(url)
                    .method("POST", body)
                    .build();
            okhttp3.Response response = client.newCall(request).execute();
            okhttp3.ResponseBody responseBody = response.body();
            if (responseBody == null) {
                return ;
            }
            JSONObject.parseObject(responseBody.string());
//            UploadTempMediaResult uploadTempMediaResult = JSONObject.parseObject(responseBody.string(), UploadTempMediaResult.class);
//            log.info("把媒体文件上传到微信服务器[OkHttpClient] 返回结果 {}", JSONObject.toJSONString(uploadTempMediaResult));

//            return uploadTempMediaResult;
        } catch (Exception e) {
//            log.info("uploadMedia e = ", e);
        }

//        return null;
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/common/download/resource")
    public void resourceDownload(String name, HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        // 本地资源路径
        String localPath = QuJiaConfig.getProfile();
        // 数据库资源地址
        String downloadPath = localPath + StringUtils.substringAfter(name, Constants.RESOURCE_PREFIX);
        // 下载名称
        String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName));
        FileUtils.writeBytes(downloadPath, response.getOutputStream());
    }
}
